import { defineComponent, reactive, ref, onMounted } from 'vue'
// import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElButton, ElCard, ElSpace, ElIcon, ElLink, ElImageViewer } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { OrderType, InfoType, imagesType, MapRefViewType } from './typings'

import styles from './index.module.scss'
import AliIcon from '~/components/AliIocn'
import MapView from './../plan/map'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'TourRecordInfo',
  props: ['id', 'goBack'],
  setup(props: { id: string; goBack: () => void }) {
    const store = useStore()
    // const router = useRouter()
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const mapRefView = ref<MapRefViewType>()
    const info = reactive<InfoType>({})
    const previewFileUrl = ref<string>()
    const recordState = useVuexGetters('tour', ['ormOrderStatusEnum'])
    const columns: TableColumnProps<OrderType>[] = [
      {
        label: '关联工单编号',
        prop: 'orderCode',
        showOverflowTooltip: true,
        minWidth: 120
      },
      {
        label: '负责人',
        prop: 'handleUserName',
        minWidth: 100
      },
      {
        label: '创建时间',
        prop: 'createTime',
        showOverflowTooltip: true,
        minWidth: 100
      },
      {
        label: '状态',
        prop: 'orderStatus',
        minWidth: 100,
        enumValues: recordState.ormOrderStatusEnum
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 100,
        unFixed: true,
        fixed: 'right',
        render: ({ row }) => (
          <ElSpace>
            <ElLink type="primary" onClick={() => infoOpen(row)}>
              详情
            </ElLink>
          </ElSpace>
        )
      }
    ]
    let list: TableColumnProps<OrderType>[] = []
    const lineArr = reactive<any>([])
    let markers = reactive<any>([])
    onMounted(() => {
      store.dispatch('tour/GetOrmOrderStatus')
      index()
    })
    //  初始化数据
    // const id = router.currentRoute.value.query.id
    const index = async () => {
      const { code, data } = await store.dispatch('tour/PatrolRecordView', { id: props.id })
      if (code === 200) {
        info.groupName = data.groupName
        info.status = data.status
        info.beginTime = data.beginTime
        info.endTime = data.endTime
        info.resultState = data.resultState
        info.leadUserName = data.leadUserName
        info.patrolRecordImageVOList = data.patrolRecordImageVOList
        list = data.orderVOList
        if (data.trackPoints) {
          const points = JSON.parse(data.trackPoints)
          if (points.length > 0) {
            for (let i = 0; i < points.length; i++) {
              const item = points[i]
              if (item.length > 0) {
                for (let j = 0; j < item.length; j++) {
                  if (j < item.length / 2) {
                    const a = [Number(item[2 * j + 1]), Number(item[2 * j])]
                    lineArr.push(a)
                  }
                }
              }
            }
          }
        }
        const array: { id: any; latitude: any; longitude: any }[] = []
        if (data.patrolTaskDetailVOList.length > 0) {
          data.patrolTaskDetailVOList.forEach((item: any) => {
            const lnglta = JSON.parse(item.phase)
            array.push({
              id: item.id,
              longitude: lnglta.coordinates[0],
              latitude: lnglta.coordinates[1]
            })
          })
          markers = array
        } else {
          markers = []
        }
      }
    }
    //  查看轨迹动画
    const polylineChange = () => {
      mapRefView.value!?.moveAlong()
    }
    //  返回
    const goBack = () => {
      props?.goBack?.()
      // router.go(-1)
    }
    //  新增工单
    const add = () => {
      // router.push({ path: '/oam/orderManage/ordersUpdate', query: { type: 'add', id: props.id } })
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/oam/orderManage',
        query: { patrolRecordId: props.id }
      })
    }
    //  工单详情
    const infoOpen = (row: OrderType) => {
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/oam/orderManage',
        query: { id: row?.orderId }
      })
      // router.push({ path: '/oam/orderManage/options', query: { id: row?.orderId } })
    }
    //  点击放大图片
    const handlePreviewFile = (file: string | undefined) => {
      previewFileUrl.value = file
    }
    //  状态转换
    const status = (value: any) => {
      switch (value) {
        case 1:
          return '进行中'
          break
        case 2:
          return '已完成'
          break
        case 3:
          return '已超时'
          break
      }
    }

    return () => {
      return (
        <ElCard class={styles['compile-card']}>
          <ElSpace class={styles['compile-tab-option-btns']}>
            <ElButton text type="primary" onClick={goBack}>
              返回上一级&nbsp;
              <AliIcon type="icon-fanhuishangyiji" />
            </ElButton>
          </ElSpace>
          <div class={styles.form}>
            <div class={styles.form_con}>
              <div class={styles.form_con_l}>
                <div class={styles.form_map}>
                  <div class={styles.form_map_moveAlong} onClick={polylineChange}>
                    查看轨迹动画
                  </div>
                  <MapView
                    ref={mapRefView}
                    id="PolylineMap"
                    iSpolyline={true}
                    lineArr={lineArr}
                    isMarkers
                    markers={markers}
                  />
                </div>
                <div class={styles.info}>
                  <div class={styles.title}>
                    <div class={styles.groupName}>{info.groupName}</div>
                    <div class={styles.status}>{status(info.status)}</div>
                  </div>
                  <div class={styles.info_item}>
                    <div class={styles.label}>巡视时间</div>
                    <div class={styles.text}>
                      {info.beginTime} -- {info.endTime}
                    </div>
                  </div>
                  <div style="display: flex;">
                    <div class={styles.info_item} style="margin-right: 40px;">
                      <div class={styles.label}>巡视人</div>
                      <div class={styles.text}>{info.leadUserName}</div>
                    </div>
                    <div class={styles.info_item}>
                      <div class={styles.label}>巡视结果</div>
                      <div class={styles.text}>{info.resultState === 1 ? '正常' : '发现缺陷'}</div>
                    </div>
                  </div>
                  <div class={styles.info_item} style="align-items: flex-start;">
                    <div class={styles.label}>巡视图片</div>
                    <div class={styles.images}>
                      {info.patrolRecordImageVOList?.map((item: imagesType) => (
                        <img onClick={() => handlePreviewFile(item.imageUrl)} src={item.imageUrl} />
                      ))}
                    </div>
                  </div>
                  {!!previewFileUrl.value && (
                    <ElImageViewer
                      teleported
                      urlList={[previewFileUrl.value]}
                      onClose={() => {
                        previewFileUrl.value = undefined
                      }}
                    />
                  )}
                </div>
              </div>
              <div class={styles.form_item}>
                <ProSaasTable
                  height="700px"
                  ref={proSaasTableRef}
                  columns={columns}
                  data={list}
                  needPagination={false}
                  headerTitle={
                    <>
                      <ElButton type="primary" onClick={add}>
                        <ElIcon>
                          <Plus />
                        </ElIcon>
                        &nbsp; 新增
                      </ElButton>
                    </>
                  }
                ></ProSaasTable>
              </div>
            </div>
          </div>
        </ElCard>
      )
    }
  }
})
